/*
 * Copyright 2012-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.delong.spring.handler.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.delong.cache.AppCache;
import com.delong.model.app.App;
import com.delong.service.AppService;
import com.delong.service.CenterTagsService;
import com.delong.service.TagsService;
import com.delong.spring.handler.BaseController;

@Controller
@RequestMapping("/app")
public class AppController extends BaseController {
	Logger log = Logger.getLogger(AppController.class);
	private AppService appService = new AppService();
	TagsService tagsService = new TagsService();
	CenterTagsService centerTagsService = new CenterTagsService();

	@RequestMapping("/list")
	public String getappList(Map<String, Object> model) {

		model.put("username", this.getUser().getUsername());
		return "app/App";
	}

	@RequestMapping(value = "/getdata", method = RequestMethod.POST)
	@ResponseBody
	public String getAppListData(Map<String, Object> model, @RequestParam(value = "id", defaultValue = "0") int id,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "search_company_id", defaultValue = "0") int companyId,
			@RequestParam(value = "search_category_id", defaultValue = "0") int categoryId,
			@RequestParam(value = "search_source", defaultValue = "-1") int source,
			@RequestParam(value = "search_status", defaultValue = "-1") int status,
			@RequestParam(value = "search_packagename", defaultValue = "") String packageName,
			@RequestParam(value = "search_big_category", defaultValue = "-1") int searchParentCategory,
			@RequestParam(value = "page", defaultValue = "1") int page,
			@RequestParam(value = "rows", defaultValue = "15") int rows) {

		if (!title.trim().equals("")) {
			title = "%" + title + "%";
		}
		if (!packageName.trim().equals("")) {
			packageName = "%" + packageName + "%";
		}
		page = page - 1;
		List<App> elements = this.appService.getListElement(id, title, companyId, categoryId, source, page * rows, rows,
				status, packageName,searchParentCategory);
		int total = this.appService.getListElementCount(id, title, companyId, categoryId, source, status, packageName,searchParentCategory);
		JSONObject result = new JSONObject();
		result.put("rows", elements);
		result.put("total", total);
		return result.toJSONString();
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public String appAdd(Map<String, Object> model,
			@RequestParam(value = "title", defaultValue = "liyang") String title,
			@RequestParam(value = "enname", defaultValue = "") String enname,
			@RequestParam(value = "versionName", defaultValue = "") String versionName,
			@RequestParam(value = "versionCode", defaultValue = "") String versionCode,
			@RequestParam(value = "packageName", defaultValue = "") String packageName,
			@RequestParam(value = "description", defaultValue = "0") String description,
			@RequestParam(value = "bytes", defaultValue = "0") int bytes,
			@RequestParam(value = "icon", defaultValue = "") String icon,
			@RequestParam(value = "downloadUrl", defaultValue = "") String downloadUrl,
			@RequestParam(value = "company_id", defaultValue = "0") int companyId,
			@RequestParam(value = "category_id", defaultValue = "0") int categoryId,
			@RequestParam(value = "screenshots_one", defaultValue = "0") String screenshotsOne,
			@RequestParam(value = "screenshots_two", defaultValue = "0") String screenshotsTwo,
			@RequestParam(value = "screenshots_three", defaultValue = "0") String screenshotsThree,
			@RequestParam(value = "screenshots_four", defaultValue = "0") String screenshotsFour,
			@RequestParam(value = "screenshots_five", defaultValue = "0") String screenshotsFive,
			@RequestParam(value = "tags", defaultValue = "0") String tags,
			@RequestParam(value = "id", defaultValue = "0") int id,
			@RequestParam(value = "source", defaultValue = "0") int source,
			@RequestParam(value = "crc32", defaultValue = "0") String crc32,
			@RequestParam(value = "md5", defaultValue = "0") String md5,
			@RequestParam(value = "star", defaultValue = "0") String star,
			@RequestParam(value = "editcomment", defaultValue = "0") String editcomment, ServletRequest req

	) {
		App element = new App();
		element.setTitle(title);
		element.setEnname(enname);
		element.setVersionName(versionName);
		element.setVersionCode(versionCode);
		element.setMd5(md5);
		element.setPackageName(packageName);
		element.setDescription(description);
		element.setBytes(bytes);
		element.setIcon(icon);
		element.setDownloadUrl(downloadUrl);
		element.setCompany_id(companyId);
		element.setScreenshots(screenshotsOne + ";" + screenshotsTwo + ";" + screenshotsThree + ";" + screenshotsFour
				+ ";" + screenshotsFive);
		element.setCategory_id(categoryId);
		element.setSource(source);
		element.setCrc32(crc32);
		element.setStar(star);
		element.setEditcomment(editcomment);
		element.setUpdateDate(new Date());
		// 分类中的应用数量增加

		HttpServletRequest request = (HttpServletRequest) req;
		String userName = request.getSession().getAttribute("username").toString();
		JSONObject result = new JSONObject();

		App packageNameOverlap = this.appService.selectElementPackageName(element.getPackageName(), id);
		if (packageNameOverlap != null) {
			result.put("code", 1);
			result.put("message", "添加失败，包名重复重复的包的id为" + packageNameOverlap.getId());
			return result.toJSONString();
		}
		if (id == 0) {
			element.setCreatdate(new Date());

			boolean opResult = appService.addElement(element);
			if (opResult) {
				result.put("code", 0);
				result.put("message", "success");
				fixTags(element.getId(), tags);
				log.info(userName + "添加应用crc32是:" + element.getCrc32());
			} else {
				result.put("code", 1);
				result.put("message", "add error");
			}

		} else {

			List<Integer> oldTagsIds = centerTagsService.getTagsId(id);
			// element.setTags(oldTagsIds);
			if (oldTagsIds.size() > 0) {
				tagsService.changeAppCount(oldTagsIds, "-1");
				centerTagsService.deleteElement(id, oldTagsIds);
			}
			element.setId(id);

			this.appService.changeElement(element);
			List<App> elements = new ArrayList<App>();
			elements.add(element);
			AppCache cache = new AppCache();
			cache.deleteApps(elements);
			fixTags(id, tags);
			log.info(userName + "修改应用crc32是:" + element.getCrc32());
			result.put("code", 0);
			result.put("message", "success");
		}

		return result.toJSONString();

	}

	private void fixTags(int appId, String TagsIds) {
		List<Integer> newAppIds = new ArrayList<Integer>();
		String[] tagsIds = TagsIds.split(",");
		for (String tagsId : tagsIds) {

			int iTagsId = Integer.valueOf(tagsId);
			newAppIds.add(iTagsId);
			centerTagsService.addElement(appId, iTagsId);

		}
		if (newAppIds.size() > 0) {
			// System.out.println("add tags count");
			tagsService.changeAppCount(newAppIds, "+1");
		}

	}

	@RequestMapping("/changestatus")
	@ResponseBody
	public String changeAppElementStatus(Map<String, Object> model,
			@RequestParam(value = "id", defaultValue = "0") int id,
			@RequestParam(value = "status", defaultValue = "0") int status, ServletRequest req

	) {

		HttpServletRequest request = (HttpServletRequest) req;
		String userName = request.getSession().getAttribute("username").toString();
		JSONObject result = new JSONObject();
		if (id > 0) {
			result.put("code", 0);

			this.appService.changeStatus(id, status);
			List<App> elements = new ArrayList<App>();
			elements.add(this.appService.getElement(id));
			AppCache cache = new AppCache();
			cache.deleteApps(elements);
		} else {
			result.put("code", 1);
		}
		log.info(userName + "修改应用状态id为:" + String.valueOf(id) + "状态为:" + String.valueOf(status));

		return result.toJSONString();
	}

	@RequestMapping("/getelement")
	@ResponseBody
	public String getElement(Map<String, Object> model, @RequestParam(value = "id", defaultValue = "0") int id) {

		App element = this.appService.getElement(id);
		List<Integer> tagsIds = this.centerTagsService.getTagsId(id);
		element.setTags(tagsIds);
		JSONObject result = new JSONObject();
		result.put("code", 0);
		result.put("data", element);
		return result.toJSONString();
	}

}
